﻿using SQLDeploy.Data.Connections;
using SQLDeploy.Data.Deployment.Steps.Tasks;
using SQLDeploy.Execution.Internal;
using SQLDeploy.Utils;
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.SqlServer.Dts.Runtime;


namespace SQLDeploy.Execution.Deployment.Steps.Tasks
{
    public class SSISInstallTask_Executor : SSISInstallTask , ITaskExecutor
    {
        private Data.Environments.Environment _Environment;

        public SSISInstallTask_Executor(SSISInstallTask TaskData) :
            base(TaskData.ParentStep)
        {
            base.ConnectionName = TaskData.ConnectionName;
            base.Name = TaskData.Name;
            base.ReplicatedOnly = TaskData.ReplicatedOnly;
            base.PackageFile = TaskData.PackageFile;
            base.InstallTo = TaskData.InstallTo;
            base.ConfigFile = TaskData.ConfigFile;
        }

        public void setEnvironment(Data.Environments.Environment executionEnvironment)
        {
            Check.notNull(executionEnvironment, "executionEnvironment");
            _Environment = executionEnvironment;
        }

        public List<Data.Connections._BaseConnection> getConnection()
        {
            if (_Environment == null)
                throw new ArgumentException("Must set Environment before calling getConnection.");
            return _Environment.getConnectionsByName(this.ConnectionName);
        }

        public bool PerformPreExecutionValidation()
        {
            //this.CurrentStatus = TaskStatus.Validating;
            bool retVal = true;
            try
            {
                if (_Environment == null)
                    throw new ArgumentException("Must set Environment before calling PerformPreExecutionValidation.");

                retVal = Common.PerformCommonTaskExectorValidation(this, _Environment);
                if (retVal)
                {
                    //TODO add any additional Checks here.
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(TaskNameHeader + "EXCEPTION: " + e.ToString());
                retVal = false;
            }
            finally
            {
                //this.CurrentStatus = TaskStatus.Idle;
            }
            //If we reached here take the retVal;
            return retVal;
        }

        public TaskExecutionResult ExecuteTask()
        {
            //CurrentStatus = TaskStatus.Executing;
            try
            {
                List<_BaseConnection> cons = getConnection();
                foreach(SQLServerConnection con in cons)
                {
                    /*
                     * Before we change anything in the package or config files lets
                     * make a temp copy of them so we don't change the orginal installation
                     * file.
                     */
                    string tmpPackageFile = generateTempFile();
                    string tmpConfigFile = null;

                    File.Copy(PackageFile, tmpPackageFile);
                    if (!string.IsNullOrEmpty(ConfigFile))
                    {
                        tmpConfigFile = generateTempFile();
                        File.Copy(ConfigFile, tmpConfigFile);
                    }

                    //TODO: perform updates to package based on config settings.

                    //Now that all changes have been applied we can handle the package installation
                    bool installed = false;
                    switch (base.InstallTo)
                    {
                        case InstallLocationEnum.SQLStore:
                            installed = InstallPackageToSQL(tmpPackageFile, tmpConfigFile, con);
                            break;
                        case InstallLocationEnum.SSISStore:
                            break;
                        case InstallLocationEnum.FileSystem:
                            break;
                        default:
                            installed = false;
                            break;
                    }
                    if (!installed)
                    {
                        return TaskExecutionResult.FAILED;
                    }
                }

                return TaskExecutionResult.SUCCESS;
            }
            catch (Exception e)
            {
                Trace.TraceError("{0} - Execution Exception: {1}", TaskNameHeader, e.ToString());
                return TaskExecutionResult.FAILED;
            }
            finally
            {
                //CurrentStatus = TaskStatus.Completed;
            }
        }

        private string generateTempFile()
        {
            return System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".tmp";
        }

        public Type RequiredConnectionType()
        {
            return typeof(SQLServerConnection);
        }


        private bool InstallPackageToSQL(string packagefile, string configfile, SQLServerConnection connection)
        {
            string fullPackagePath = PackagePath;
            string[] paths = new string[] { };
            if (fullPackagePath.Length > 0 && !fullPackagePath.EndsWith("\\"))
            {
                fullPackagePath += "\\" + PackageName;
                paths = PackagePath.Split('\\');
            }

            Application ssisApp = new Application();
            //Does the folderPath exist?
            if (!ssisApp.FolderExistsOnSqlServer("\\" + PackagePath, connection.DataSource,
                    connection.IntegratedSecurity ? null : connection.UserId,
                    connection.IntegratedSecurity ? null : connection.Password))
            {
                try
                {
                    string currentPath = "\\";
                    string lastPath = "\\";
                    for (int i = 0; i < paths.Length; i++)
                    {
                        currentPath += paths[i];
                        if (!ssisApp.FolderExistsOnSqlServer(currentPath,
                                connection.DataSource,
                                connection.IntegratedSecurity ? null : connection.UserId,
                                connection.IntegratedSecurity ? null : connection.Password))
                        {
                            ssisApp.CreateFolderOnSqlServer(lastPath, paths[i],
                                connection.DataSource,
                                connection.IntegratedSecurity ? null : connection.UserId,
                                connection.IntegratedSecurity ? null : connection.Password);
                        }
                        lastPath = currentPath;
                        currentPath += "\\";
                    }
                }
                catch (Exception e)
                {
                    Trace.TraceError("{0}Failure to create requested Folder Structure: {1}",
                        TaskNameHeader, e.ToString());
                    return false;
                }
            }


            //Load the packages
            Package package = null;
            try
            {
                package = ssisApp.LoadPackage(packagefile, null);
                package.Name = PackageName;
            }
            catch (Exception e)
            {
                Trace.TraceError("{0}Failed to load SSIS Package : {1}",
                    TaskNameHeader, e.ToString());
                return false;
            }
            
            
            //Check if the package exists, if so remove it.
            try
            {
                if (ssisApp.ExistsOnSqlServer(fullPackagePath, connection.DataSource,
                connection.IntegratedSecurity ? null : connection.UserId,
                connection.IntegratedSecurity ? null : connection.Password))
                {
                    try
                    {
                        ssisApp.RemoveFromSqlServer(fullPackagePath, connection.DataSource,
                        connection.IntegratedSecurity ? null : connection.UserId,
                        connection.IntegratedSecurity ? null : connection.Password);
                    }
                    catch (Exception e)
                    {
                        Trace.TraceError("{0}FailedTo remove existing version of package: {1}",
                            TaskNameHeader, e.ToString());
                        return false;
                    }
                }
                //Install the package
                ssisApp.SaveToSqlServerAs(package, null, fullPackagePath, connection.DataSource,
                    connection.IntegratedSecurity ? null : connection.UserId,
                    connection.IntegratedSecurity ? null : connection.Password);

                return true;
            }
            catch (Exception e)
            {
                Trace.TraceError("{0}Failed to install SSIS package to SQL: {1}",
                    TaskNameHeader, e.ToString());
                return false;
            }
            
        }

    }
}
